package org.vshe.improve.pattern.effectivej.ch2;

import java.util.HashMap;
import java.util.Map;

public class Services {
	private static Map<String, ServiceProvider> providers
		= new HashMap<String, ServiceProvider>();

	private static final String DEFAULT_PROVIDER_KEY = "<def/>";

	private Services() {
	}

	private static void registerDefaultProvider(ServiceProvider provider) {
		registerProvider(DEFAULT_PROVIDER_KEY, provider);
	}

	private static void registerProvider(String key, ServiceProvider provider) {
		providers.put(key, provider);
	}

	public static Service newInstance() {
		return newInstance(DEFAULT_PROVIDER_KEY);
	}

	public static Service newInstance(String key) {
		ServiceProvider serviceProvider = providers.get(key);
		if (serviceProvider == null) {
			throw new IllegalStateException(
					"Provider is not registered for creating new instances.");
		}

		return serviceProvider.newInstance();
	}

}
